<template>
  <div class="database-management">
    <a-tabs default-active-key="1" @change="handleTabChange">
      <a-tab-pane key="1" tab="数据库列表" style="padding:0 20px 20px 20px;">
        <div class="action-bar" style="padding-bottom:20px;">
          <a-button type="primary" @click="showAddModal">
            <a-icon type="plus" /> 新增数据库
          </a-button>
          <a-button :disabled="!selectedRowKeys.length" @click="handleBatchSync" :loading="batchSyncing">
            <a-icon type="sync" /> 批量同步
          </a-button>
          <a-input-search
            placeholder="输入数据库名称搜索"
            style="width: 300px; float: right"
            @search="handleSearch"
          />
        </div>
        
        <a-table
          :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          :columns="columns"
          :data-source="databaseList"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
		  :scroll="{ x: true }"
          @change="handleTableChange"
        >
          <span slot="type" slot-scope="type">
            <a-tag :color="getDbTypeColor(type)">
              {{ getDbTypeName(type) }}
            </a-tag>
          </span>
          
          <span slot="status" slot-scope="status">
            <a-badge :status="status === 1 ? 'processing' : 'error'" :text="status === 1 ? '已连接' : '未连接'" />
          </span>
          
          <span slot="syncMode" slot-scope="syncMode, record">
            <a-switch
              :checked="syncMode === 2"
              checked-children="自动"
              un-checked-children="手动"
              @change="(checked) => changeSyncMode(checked, record)"
            />
          </span>
          
          <span slot="lastSyncTime" slot-scope="lastSyncTime">
            {{ lastSyncTime || '从未同步' }}
          </span>
          
          <span slot="action" slot-scope="text, record">
            <a @click="handleSync(record)">同步</a>
            <a-divider type="vertical" />
            <a @click="showEditModal(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="showPushModal(record)">推送</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个数据库配置吗?"
              @confirm="handleDelete(record.id)"
              ok-text="确定"
              cancel-text="取消"
            >
              <a href="#" style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </a-tab-pane>
      
      <a-tab-pane key="2" tab="同步日志" force-render style="padding:0 20px 20px 20px;">
        <a-table
          :columns="logColumns"
          :data-source="syncLogs"
          :pagination="logPagination"
          :loading="logLoading"
          row-key="id"
        >
          <span slot="result" slot-scope="result">
            <a-tag :color="result === '成功' ? 'green' : 'red'">
              {{ result }}
            </a-tag>
          </span>
          
          <span slot="detail" slot-scope="text, record">
            <a @click="showLogDetail(record)">查看详情</a>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 新增/编辑数据库模态框 -->
    <a-modal
      :title="isEdit ? '编辑数据库配置' : '新增数据库配置'"
      :visible="dbModalVisible"
      :confirm-loading="modalConfirmLoading"
      @ok="handleDbModalOk"
      @cancel="handleDbModalCancel"
      width="700px"
    >
      <a-form-model
        ref="dbForm"
        :model="dbForm"
        :rules="dbRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="数据库名称" prop="name">
          <a-input v-model="dbForm.name" placeholder="请输入数据库名称" />
        </a-form-model-item>
        
        <a-form-model-item label="数据库类型" prop="type">
          <a-select v-model="dbForm.type" placeholder="请选择数据库类型" @change="handleDbTypeChange">
            <a-select-option v-for="(type,index) in dbTypes " :key="index" :value="type.value">
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        
        <a-form-model-item label="主机地址" prop="host">
          <a-input v-model="dbForm.host" placeholder="请输入数据库主机地址" />
        </a-form-model-item>
        
        <a-form-model-item label="端口" prop="port">
          <a-input-number v-model="dbForm.port" :min="1" :max="65535" style="width: 100%" />
        </a-form-model-item>
        
        <a-form-model-item label="数据库名称" prop="database">
          <a-input v-model="dbForm.database" placeholder="请输入要连接的数据库名称" />
        </a-form-model-item>
        
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="dbForm.username" placeholder="请输入数据库用户名" />
        </a-form-model-item>
        
        <a-form-model-item label="密码" prop="password">
          <a-input-password v-model="dbForm.password" placeholder="请输入数据库密码" />
        </a-form-model-item>
        
        <a-form-model-item label="同步模式" prop="syncMode">
          <a-radio-group v-model="dbForm.syncMode">
            <a-radio :value="1">手动同步</a-radio>
            <a-radio :value="2">自动同步</a-radio>
          </a-radio-group>
        </a-form-model-item>
        
        <a-form-model-item v-if="dbForm.syncMode === 2" label="同步频率" prop="syncCron">
          <a-select v-model="dbForm.syncCron" placeholder="请选择同步频率">
            <a-select-option value="0 0/30 * * * ?">每30分钟</a-select-option>
            <a-select-option value="0 0 * * * ?">每小时</a-select-option>
            <a-select-option value="0 0 0/6 * * ?">每6小时</a-select-option>
            <a-select-option value="0 0 12 * * ?">每天中午12点</a-select-option>
            <a-select-option value="0 0 0 * * ?">每天午夜</a-select-option>
          </a-select>
        </a-form-model-item>
        
        <a-form-model-item label="描述" prop="description">
          <a-textarea v-model="dbForm.description" placeholder="请输入数据库描述信息" :rows="3" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    
    <!-- 数据推送模态框 -->
    <a-modal
      title="数据推送配置"
      :visible="pushModalVisible"
      :confirm-loading="pushConfirmLoading"
      @ok="handlePushModalOk"
      @cancel="handlePushModalCancel"
      width="800px"
    >
      <a-form-model
        ref="pushForm"
        :model="pushForm"
        :rules="pushRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item label="推送目标" prop="target">
          <a-select v-model="pushForm.target" placeholder="请选择推送目标">
            <a-select-option value="api">API接口</a-select-option>
            <a-select-option value="kafka">Kafka消息队列</a-select-option>
            <a-select-option value="rabbitmq">RabbitMQ</a-select-option>
            <a-select-option value="oss">OSS存储</a-select-option>
          </a-select>
        </a-form-model-item>
        
        <template v-if="pushForm.target === 'api'">
          <a-form-model-item label="API地址" prop="apiUrl">
            <a-input v-model="pushForm.apiUrl" placeholder="请输入API地址" />
          </a-form-model-item>
          
          <a-form-model-item label="请求方法" prop="apiMethod">
            <a-select v-model="pushForm.apiMethod">
              <a-select-option value="POST">POST</a-select-option>
              <a-select-option value="PUT">PUT</a-select-option>
              <a-select-option value="PATCH">PATCH</a-select-option>
            </a-select>
          </a-form-model-item>
          
          <a-form-model-item label="认证方式" prop="apiAuthType">
            <a-select v-model="pushForm.apiAuthType">
              <a-select-option value="none">无认证</a-select-option>
              <a-select-option value="basic">Basic认证</a-select-option>
              <a-select-option value="bearer">Bearer Token</a-select-option>
            </a-select>
          </a-form-model-item>
          
          <template v-if="pushForm.apiAuthType !== 'none'">
            <a-form-model-item label="用户名/Token" prop="apiAuthKey">
              <a-input v-model="pushForm.apiAuthKey" placeholder="请输入用户名或Token" />
            </a-form-model-item>
            
            <a-form-model-item v-if="pushForm.apiAuthType === 'basic'" label="密码" prop="apiAuthSecret">
              <a-input-password v-model="pushForm.apiAuthSecret" placeholder="请输入密码" />
            </a-form-model-item>
          </template>
        </template>
        
        <template v-else-if="pushForm.target === 'kafka' || pushForm.target === 'rabbitmq'">
          <a-form-model-item label="服务器地址" prop="mqServers">
            <a-input v-model="pushForm.mqServers" placeholder="请输入服务器地址，多个用逗号分隔" />
          </a-form-model-item>
          
          <a-form-model-item label="Topic/Queue" prop="mqTopic">
            <a-input v-model="pushForm.mqTopic" placeholder="请输入Topic或Queue名称" />
          </a-form-model-item>
          
          <a-form-model-item v-if="pushForm.target === 'kafka'" label="消息Key" prop="mqKey">
            <a-input v-model="pushForm.mqKey" placeholder="请输入消息Key（可选）" />
          </a-form-model-item>
        </template>
        
        <template v-else-if="pushForm.target === 'oss'">
          <a-form-model-item label="OSS类型" prop="ossType">
            <a-select v-model="pushForm.ossType">
              <a-select-option value="aliyun">阿里云OSS</a-select-option>
              <a-select-option value="qcloud">腾讯云COS</a-select-option>
              <a-select-option value="aws">AWS S3</a-select-option>
            </a-select>
          </a-form-model-item>
          
          <a-form-model-item label="Bucket名称" prop="ossBucket">
            <a-input v-model="pushForm.ossBucket" placeholder="请输入Bucket名称" />
          </a-form-model-item>
          
          <a-form-model-item label="文件路径" prop="ossPath">
            <a-input v-model="pushForm.ossPath" placeholder="请输入文件路径，如: data/export/" />
          </a-form-model-item>
        </template>
        
        <a-form-model-item label="推送数据表" prop="tables">
          <a-transfer
            :data-source="tableList"
            :target-keys="pushForm.tables"
            :render="item => item.title"
            @change="handleTableTransferChange"
          />
        </a-form-model-item>
        
        <a-form-model-item label="推送频率" prop="pushFrequency">
          <a-select v-model="pushForm.pushFrequency" placeholder="请选择推送频率">
            <a-select-option value="realtime">实时推送</a-select-option>
            <a-select-option value="daily">每日一次</a-select-option>
            <a-select-option value="hourly">每小时一次</a-select-option>
            <a-select-option value="manual">手动推送</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    
    <!-- 日志详情模态框 -->
    <a-modal
      title="同步日志详情"
      :visible="logDetailVisible"
      :footer="null"
      @cancel="logDetailVisible = false"
      width="800px"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="数据库名称">{{ currentLog.dbName }}</a-descriptions-item>
        <a-descriptions-item label="同步时间">{{ currentLog.syncTime }}</a-descriptions-item>
        <a-descriptions-item label="同步结果">
          <a-tag :color="currentLog.result === '成功' ? 'green' : 'red'">
            {{ currentLog.result }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="同步模式">{{ currentLog.syncMode }}</a-descriptions-item>
        <a-descriptions-item label="同步数据量">{{ currentLog.dataCount }}</a-descriptions-item>
        <a-descriptions-item label="耗时">{{ currentLog.duration }}</a-descriptions-item>
        <a-descriptions-item label="日志详情">
          <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 300px; overflow: auto;">{{ currentLog.detail }}</pre>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    
    <!-- 测试连接结果通知 -->
    <a-notification
      v-if="testResultVisible"
      :key="testResult.type"
      :type="testResult.type"
      :message="testResult.message"
      :description="testResult.description"
      @close="testResultVisible = false"
    />
  </div>
</template>

<script>
export default {
  name: 'DatabaseManagement',
  data() {
    return {
      // 数据库列表相关
      selectedRowKeys: [],
      databaseList: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      searchText: '',
      
      // 同步日志相关
      syncLogs: [],
      logLoading: false,
      logPagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      
      // 数据库类型选项
      dbTypes: [
        { value: 1, label: 'MySQL' },
        { value: 2, label: 'Oracle' },
        { value: 3, label: 'SQL Server' },
        { value: 4, label: 'PostgreSQL' },
        { value: 5, label: 'MongoDB' },
        { value: 6, label: 'Redis' },
        { value: 7, label: 'Elasticsearch' },
      ],
      
      // 数据库表格列配置
      columns: [
        {
          title: '数据库名称',
          dataIndex: 'name',
          key: 'name',
          width: 180,
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          width: 100,
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '连接地址',
          dataIndex: 'host',
          key: 'host',
          width: 200,
          customRender: (text, record) => `${record.host}:${record.port}/${record.database}`,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '同步模式',
          dataIndex: 'syncMode',
          key: 'syncMode',
          width: 120,
          scopedSlots: { customRender: 'syncMode' },
        },
        {
          title: '最后同步时间',
          dataIndex: 'lastSyncTime',
          key: 'lastSyncTime',
          width: 180,
          scopedSlots: { customRender: 'lastSyncTime' },
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
          ellipsis: true,
        },
        {
          title: '操作',
          key: 'action',
		   fixed: 'right',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      
      // 日志表格列配置
      logColumns: [
        {
          title: '数据库名称',
          dataIndex: 'dbName',
          key: 'dbName',
          width: 150,
        },
        {
          title: '同步时间',
          dataIndex: 'syncTime',
          key: 'syncTime',
          width: 180,
        },
        {
          title: '同步模式',
          dataIndex: 'syncMode',
          key: 'syncMode',
          width: 100,
        },
        {
          title: '结果',
          dataIndex: 'result',
          key: 'result',
          width: 100,
          scopedSlots: { customRender: 'result' },
        },
        {
          title: '数据量',
          dataIndex: 'dataCount',
          key: 'dataCount',
          width: 100,
        },
        {
          title: '耗时',
          dataIndex: 'duration',
          key: 'duration',
          width: 100,
        },
        {
          title: '操作',
          key: 'detail',
          width: 100,
          scopedSlots: { customRender: 'detail' },
        },
      ],
      
      // 数据库模态框相关
      dbModalVisible: false,
      isEdit: false,
      modalConfirmLoading: false,
      dbForm: {
        id: null,
        name: '',
        type: 1,
        host: '',
        port: 3306,
        database: '',
        username: '',
        password: '',
        syncMode: 1,
        syncCron: '0 0 * * * ?',
        description: '',
      },
      dbRules: {
        name: [{ required: true, message: '请输入数据库名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
        host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
        port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
        database: [{ required: true, message: '请输入数据库名称', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      
      // 推送模态框相关
      pushModalVisible: false,
      pushConfirmLoading: false,
      pushForm: {
        target: 'api',
        tables: [],
        // API相关
        apiUrl: '',
        apiMethod: 'POST',
        apiAuthType: 'none',
        apiAuthKey: '',
        apiAuthSecret: '',
        // 消息队列相关
        mqServers: '',
        mqTopic: '',
        mqKey: '',
        // OSS相关
        ossType: 'aliyun',
        ossBucket: '',
        ossPath: '',
        // 其他
        pushFrequency: 'realtime',
      },
      pushRules: {
        target: [{ required: true, message: '请选择推送目标', trigger: 'change' }],
        apiUrl: [{ required: true, message: '请输入API地址', trigger: 'blur' }],
        mqServers: [{ required: true, message: '请输入服务器地址', trigger: 'blur' }],
        mqTopic: [{ required: true, message: '请输入Topic/Queue名称', trigger: 'blur' }],
        ossBucket: [{ required: true, message: '请输入Bucket名称', trigger: 'blur' }],
        ossPath: [{ required: true, message: '请输入文件路径', trigger: 'blur' }],
      },
      tableList: [],
      
      // 日志详情相关
      logDetailVisible: false,
      currentLog: {},
      
      // 测试连接结果
      testResultVisible: false,
      testResult: {},
      
      // 批量同步状态
      batchSyncing: false,
    };
  },
  created() {
    this.fetchDatabaseList();
    this.fetchSyncLogs();
    this.generateTableList();
  },
  methods: {
    // 获取数据库列表
    fetchDatabaseList() {
      this.loading = true;
      // 模拟API请求
      setTimeout(() => {
        this.databaseList = [
          {
            id: 1,
            name: '核心业务数据库',
            type: 1,
            host: '192.168.1.100',
            port: 3306,
            database: 'core_business',
            username: 'admin',
            status: 1,
            syncMode: 2,
            lastSyncTime: '2023-05-15 14:30:22',
            description: '公司核心业务系统数据库，包含订单、用户等关键数据',
          },
          {
            id: 2,
            name: '用户中心数据库',
            type: 1,
            host: '192.168.1.101',
            port: 3306,
            database: 'user_center',
            username: 'admin',
            status: 1,
            syncMode: 1,
            lastSyncTime: '2023-05-16 09:15:45',
            description: '用户认证、权限管理相关数据',
          },
          {
            id: 3,
            name: '日志分析数据库',
            type: 4,
            host: '192.168.1.102',
            port: 5432,
            database: 'log_analysis',
            username: 'analyst',
            status: 1,
            syncMode: 2,
            lastSyncTime: '2023-05-16 12:00:00',
            description: '存储系统日志用于分析',
          },
          {
            id: 4,
            name: '缓存数据库',
            type: 6,
            host: '192.168.1.103',
            port: 6379,
            database: '0',
            username: '',
            status: 0,
            syncMode: 1,
            lastSyncTime: '',
            description: '系统缓存数据',
          },
          {
            id: 5,
            name: '文档数据库',
            type: 5,
            host: '192.168.1.104',
            port: 27017,
            database: 'document_db',
            username: 'mongo_admin',
            status: 1,
            syncMode: 2,
            lastSyncTime: '2023-05-16 11:30:15',
            description: '非结构化文档数据存储',
          },
          {
            id: 6,
            name: '数据仓库',
            type: 3,
            host: '192.168.1.105',
            port: 1433,
            database: 'data_warehouse',
            username: 'dw_user',
            status: 1,
            syncMode: 2,
            lastSyncTime: '2023-05-16 00:00:00',
            description: 'BI报表和分析使用的数据仓库',
          },
          {
            id: 7,
            name: '搜索服务',
            type: 7,
            host: '192.168.1.106',
            port: 9200,
            database: 'product_index',
            username: 'elastic',
            status: 1,
            syncMode: 1,
            lastSyncTime: '2023-05-15 18:45:30',
            description: '商品搜索索引',
          },
        ];
        this.pagination.total = this.databaseList.length;
        this.loading = false;
      }, 500);
    },
    
    // 获取同步日志
    fetchSyncLogs() {
      this.logLoading = true;
      // 模拟API请求
      setTimeout(() => {
        this.syncLogs = [
          {
            id: 1,
            dbName: '核心业务数据库',
            syncTime: '2023-05-16 14:30:22',
            syncMode: '自动同步',
            result: '成功',
            dataCount: '1,245条',
            duration: '45秒',
            detail: '同步完成，共处理1245条数据，其中新增856条，更新389条。',
          },
          {
            id: 2,
            dbName: '用户中心数据库',
            syncTime: '2023-05-16 09:15:45',
            syncMode: '手动同步',
            result: '成功',
            dataCount: '532条',
            duration: '32秒',
            detail: '用户数据同步完成，新增用户128个，更新用户信息404条。',
          },
          {
            id: 3,
            dbName: '文档数据库',
            syncTime: '2023-05-16 11:30:15',
            syncMode: '自动同步',
            result: '成功',
            dataCount: '2,187条',
            duration: '1分12秒',
            detail: '文档同步完成，新增文档1567个，更新620个。',
          },
          {
            id: 4,
            dbName: '数据仓库',
            syncTime: '2023-05-16 00:00:00',
            syncMode: '自动同步',
            result: '成功',
            dataCount: '15,672条',
            duration: '5分23秒',
            detail: '每日数据仓库同步完成，处理15672条数据。',
          },
          {
            id: 5,
            dbName: '缓存数据库',
            syncTime: '2023-05-15 16:20:18',
            syncMode: '手动同步',
            result: '失败',
            dataCount: '0条',
            duration: '3秒',
            detail: '连接Redis失败: Connection refused. 请检查Redis服务是否正常运行。',
          },
        ];
        this.logPagination.total = this.syncLogs.length;
        this.logLoading = false;
      }, 500);
    },
    
    // 生成表列表用于推送选择
    generateTableList() {
      const tables = [];
      for (let i = 0; i < 20; i++) {
        tables.push({
          key: `table_${i}`,
          title: `数据表_${i}`,
          description: `描述信息_${i}`,
        });
      }
      this.tableList = tables;
    },
    
    // 表格选择变化
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    
    // 表格分页/排序变化
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.fetchDatabaseList();
    },
    
    // 日志表格分页变化
    handleLogTableChange(pagination) {
      this.logPagination = pagination;
      this.fetchSyncLogs();
    },
    
    // 搜索数据库
    handleSearch(value) {
      this.searchText = value;
      this.pagination.current = 1;
      this.fetchDatabaseList();
    },
    
    // 切换标签页
    handleTabChange(key) {
      console.log('切换到标签页:', key);
    },
    
    // 显示新增数据库模态框
    showAddModal() {
      this.isEdit = false;
      this.dbForm = {
        id: null,
        name: '',
        type: 1,
        host: '',
        port: 3306,
        database: '',
        username: '',
        password: '',
        syncMode: 1,
        syncCron: '0 0 * * * ?',
        description: '',
      };
      this.dbModalVisible = true;
      this.$nextTick(() => {
        this.$refs.dbForm && this.$refs.dbForm.clearValidate();
      });
    },
    
    // 显示编辑数据库模态框
    showEditModal(record) {
      this.isEdit = true;
      this.dbForm = {
        ...record,
        password: '******', // 密码不显示真实值
      };
      this.dbModalVisible = true;
      this.$nextTick(() => {
        this.$refs.dbForm && this.$refs.dbForm.clearValidate();
      });
    },
    
    // 数据库模态框确定
    handleDbModalOk() {
      this.$refs.dbForm.validate(valid => {
        if (valid) {
          this.modalConfirmLoading = true;
          // 模拟API请求
          setTimeout(() => {
            this.$message.success(this.isEdit ? '数据库配置更新成功' : '数据库配置添加成功');
            this.dbModalVisible = false;
            this.modalConfirmLoading = false;
            this.fetchDatabaseList();
          }, 800);
        }
      });
    },
    
    // 数据库模态框取消
    handleDbModalCancel() {
      this.dbModalVisible = false;
    },
    
    // 显示推送配置模态框
    showPushModal(record) {
      this.pushForm = {
        target: 'api',
        tables: ['table_1', 'table_3', 'table_5'],
        apiUrl: '',
        apiMethod: 'POST',
        apiAuthType: 'none',
        apiAuthKey: '',
        apiAuthSecret: '',
        mqServers: '',
        mqTopic: '',
        mqKey: '',
        ossType: 'aliyun',
        ossBucket: '',
        ossPath: '',
        pushFrequency: 'realtime',
      };
      this.pushModalVisible = true;
      this.$nextTick(() => {
        this.$refs.pushForm && this.$refs.pushForm.clearValidate();
      });
    },
    
    // 推送模态框确定
    handlePushModalOk() {
      this.$refs.pushForm.validate(valid => {
        if (valid) {
          this.pushConfirmLoading = true;
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('推送配置保存成功');
            this.pushModalVisible = false;
            this.pushConfirmLoading = false;
          }, 800);
        }
      });
    },
    
    // 推送模态框取消
    handlePushModalCancel() {
      this.pushModalVisible = false;
    },
    
    // 表选择变化
    handleTableTransferChange(targetKeys) {
      this.pushForm.tables = targetKeys;
    },
    
    // 显示日志详情
    showLogDetail(record) {
      this.currentLog = record;
      this.logDetailVisible = true;
    },
    
    // 数据库类型变化
    handleDbTypeChange(value) {
      // 根据不同类型设置默认端口
      const defaultPorts = {
        1: 3306, // MySQL
        2: 1521, // Oracle
        3: 1433, // SQL Server
        4: 5432, // PostgreSQL
        5: 27017, // MongoDB
        6: 6379, // Redis
        7: 9200, // Elasticsearch
      };
      this.dbForm.port = defaultPorts[value] || 3306;
    },
    
    // 获取数据库类型名称
    getDbTypeName(type) {
      const typeMap = {
        1: 'MySQL',
        2: 'MySQL',
        3: 'MySQL',
        4: 'MySQL',
        5: 'MySQL',
        6: 'MySQL',
        7: 'MySQL',
      };
      return typeMap[type] || '未知';
    },
    
    // 获取数据库类型颜色
    getDbTypeColor(type) {
      const colorMap = {
        1: 'blue',
        2: 'red',
        3: 'cyan',
        4: 'geekblue',
        5: 'green',
        6: 'volcano',
        7: 'purple',
      };
      return colorMap[type] || 'default';
    },
    
    // 测试数据库连接
    testConnection() {
      this.modalConfirmLoading = true;
      // 模拟API请求
      setTimeout(() => {
        const success = Math.random() > 0.3; // 70%成功率
        this.testResult = {
          type: success ? 'success' : 'error',
          message: success ? '连接成功' : '连接失败',
          description: success 
            ? '数据库连接测试成功，可以正常访问。' 
            : '无法连接到数据库，请检查配置信息是否正确。',
        };
        this.testResultVisible = true;
        this.modalConfirmLoading = false;
      }, 1500);
    },
    
    // 同步单个数据库
    handleSync(record) {
      this.$confirm({
        title: '确认同步',
        content: `确定要同步数据库"${record.name}"吗?`,
        onOk: () => {
          const loading = this.$message.loading('同步中...', 0);
          // 模拟API请求
          setTimeout(() => {
            loading();
            this.$message.success(`数据库"${record.name}"同步成功`);
            // 更新最后同步时间
            const now = new Date();
            record.lastSyncTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
            this.fetchSyncLogs();
          }, 2000);
        },
      });
    },
    
    // 批量同步
    handleBatchSync() {
      this.$confirm({
        title: '确认批量同步',
        content: `确定要同步选中的${this.selectedRowKeys.length}个数据库吗?`,
        onOk: () => {
          this.batchSyncing = true;
          // 模拟API请求
          setTimeout(() => {
            this.batchSyncing = false;
            this.$message.success(`成功同步${this.selectedRowKeys.length}个数据库`);
            // 更新最后同步时间
            const now = new Date();
            const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
            this.databaseList.forEach(db => {
              if (this.selectedRowKeys.includes(db.id)) {
                db.lastSyncTime = timeStr;
              }
            });
            this.selectedRowKeys = [];
            this.fetchSyncLogs();
          }, 3000);
        },
      });
    },
    
    // 删除数据库配置
    handleDelete(id) {
      // 模拟API请求
      setTimeout(() => {
        this.$message.success('数据库配置删除成功');
        this.databaseList = this.databaseList.filter(db => db.id !== id);
        this.pagination.total = this.databaseList.length;
      }, 800);
    },
    
    // 更改同步模式
    changeSyncMode(checked, record) {
      const newMode = checked ? 2 : 1;
      // 模拟API请求
      setTimeout(() => {
        record.syncMode = newMode;
        this.$message.success(`已${checked ? '启用' : '禁用'}自动同步模式`);
      }, 500);
    },
  },
};
</script>
